package com.xiaoq.feature.endpoint;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.MathUtil;
import com.xiaoq.feature.entity.ShopFoodEntity;
import com.xiaoq.feature.entity.ShopMenusEntity;
import com.xiaoq.feature.entity.VegetRecomEntity;
import com.xiaoq.feature.repository.IShopFoodRepository;
import com.xiaoq.feature.service.IShopFoodService;
import com.xiaoq.feature.service.IVegetRecomService;
import com.xiaoq.feature.vo.ShopFoodReptileVo;
import com.xiaoq.feature.vo.ShopFoodVo;
import com.xiaoq.feature.vo.VegetRecomVo;
import com.xiaoq.vo.PagingVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@Api(tags={"必吃相关接口"})
@RestController
@RequestMapping("/api/v1/sites")
public class ShopFoodEndpoint {
	
	@Autowired
	private IShopFoodService shopfoodSer;
	
	@Autowired
	private IVegetRecomService vegetRecomSer;
	
	@Autowired
	private IShopFoodRepository shopFoodRep;
	
	
	private static final Logger LOG = LoggerFactory.getLogger(ShopFoodEndpoint.class);
	
	private class ShopFoodListResponse extends GenericListResponse<ShopFoodVo>{}
	
	private class ShopFoodDataResponse extends GenericDataResponse<ShopFoodVo> {}
	
	private class VegetRecomListResponse extends GenericListResponse<VegetRecomVo> {}
	
	@ApiOperation(value = "必吃ES测试", notes = "必吃ES测试")
	@ApiResponses({ @ApiResponse(code = 200, response = ShopFoodListResponse.class, message = "必吃ES测试") })
	@GetMapping(value="/es", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> findShopFoodES(String text, PagingVo pagingVo){
		
		List<ShopFoodEntity> shopFoodList = shopfoodSer.findShopFoodFromEsByText(text, pagingVo);
		List<ShopFoodVo> shopFoodVoList = new ArrayList<>();
		ShopFoodVo shopFoodVo = null;
		for(ShopFoodEntity shopFood:shopFoodList){
			shopFoodVo = new ShopFoodVo();
			BeanUtils.copyProperties(shopFood, shopFoodVo);
			shopFoodVoList.add(shopFoodVo);
		}
		
		return ShopFoodListResponse.listNoCount(shopFoodVoList);
		
	}
	
	@ApiOperation(value = "添加一条美食商店", notes = "添加一条美食商店")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "添加一条美食商店") })
	@RequestMapping(value = "/shop_food", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST)
	public ResponseEntity<?> addShopFood(@RequestBody ShopFoodEntity shopFood){
		shopfoodSer.save(shopFood);
		return GenericResponse.ok();
		
	}
	
	@ApiOperation(value = "获取景区必吃详情", notes = "获取景区必吃详情")
	@ApiResponses({ @ApiResponse(code = 200, response = ShopFoodDataResponse.class, message = "获取景区必吃详情") })
	@GetMapping(value="/details", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> findShopFoodDetail(@RequestParam(value="shopFoodId")String shopFoodId){
		ShopFoodEntity shopFood = shopfoodSer.findShopFood(shopFoodId);
		ShopFoodVo shopFoodVo = new ShopFoodVo();
		BeanUtils.copyProperties(shopFood, shopFoodVo);
		return ShopFoodDataResponse.okWithData(shopFoodVo);
		
	}
	@ApiOperation(value = "地图上餐饮显示", notes = "地图上餐饮显示")
	@ApiResponses({ @ApiResponse(code = 200, response = ShopFoodListResponse.class, message = "地图上餐饮显示") })
	@GetMapping(value="/features", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> findShopFoodList2Map(
			@RequestParam(value="longitude",required=true)@ApiParam(value="景区经度",required=true)Double longitude,
			@RequestParam(value="latitude",required=true)@ApiParam(value="景区纬度",required=true)Double latitude,
			@RequestParam(value="sitesId",required=false)@ApiParam(value="景区Id",required=false)String sitesId){
		
		List<ShopFoodEntity> shopFoodList = shopfoodSer.findShopFoodList(longitude, latitude);
		List<ShopFoodVo> shopFoodVoList = new ArrayList<>();
		ShopFoodVo shopFoodVo = null;
		for(ShopFoodEntity shopFood:shopFoodList){
			shopFoodVo = new ShopFoodVo();
			BeanUtils.copyProperties(shopFood, shopFoodVo);
			shopFoodVoList.add(shopFoodVo);
		}
		
		return ShopFoodListResponse.listNoCount(shopFoodVoList);
		
	}
	
	@ApiOperation(value = "修改经纬度", notes = "修改经纬度")
	@ApiResponses({ @ApiResponse(code = 200, response = ShopFoodListResponse.class, message = "修改经纬度") })
	@GetMapping(value="/change", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> changeLoc(){
		shopFoodRep.addLoc();
		return GenericResponse.ok();
		
	}
	
	@ApiOperation(value = "获取景区附近的特色必吃", notes = "获取景区附近的特色必吃")
	@ApiResponses({ @ApiResponse(code = 200, response = ShopFoodListResponse.class, message = "获取景区附近的特色必吃") })
	@GetMapping(value="/feature", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> findShopFoodList(
			@RequestParam(value="longitude",required=true)@ApiParam(value="景区经度",required=true)Double longitude,
			@RequestParam(value="latitude",required=true)@ApiParam(value="景区纬度",required=true)Double latitude,
			@RequestParam(value="sitesId",required=false)@ApiParam(value="景区Id",required=false)String sitesId,
			@RequestParam(value="localLongitude",required=false)@ApiParam(value="当前经度",required=false)Double localLongitude,
			@RequestParam(value="localLatitude",required=false)@ApiParam(value="当前纬度",required=false)Double localLatitude,
			@ModelAttribute(value="pvo")PagingVo pvo){
		List<ShopFoodEntity> shopFoodList = shopfoodSer.findShopFoodList(longitude, latitude, localLongitude,localLatitude,pvo);
		List<ShopFoodVo> shopFoodVoList = new ArrayList<>();
		ShopFoodVo shopFoodVo = null;
		for(ShopFoodEntity shopFood:shopFoodList){
			shopFoodVo = new ShopFoodVo();
			BeanUtils.copyProperties(shopFood, shopFoodVo);
			if(localLongitude!=null&&localLatitude!=null&&localLongitude!=0.00&&localLatitude!=0.00){
				Double shopLongitude = shopFoodVo.getLongitude();
				Double shopLatitude = shopFoodVo.getLatitude();
				Double distance = MathUtil.distance(localLongitude, localLatitude, shopLongitude, shopLatitude);
				shopFoodVo.setDistance(distance);
				String distanceString = MathUtil.distance(distance);
				shopFoodVo.setDistanceString(distanceString);
			}
			shopFoodVoList.add(shopFoodVo);
		}
		if (shopFoodVoList != null && shopFoodVoList.size() > 1) {

			Collections.sort(shopFoodVoList, new Comparator<ShopFoodVo>() {

				@Override
				public int compare(ShopFoodVo shopFoodVo1, ShopFoodVo shopFoodVo2) {
					Double status1 = shopFoodVo1.getAvgScore() - shopFoodVo2.getAvgScore();
					if (status1 == 0.0) {
						Double status2 = shopFoodVo1.getDistance() - shopFoodVo2.getDistance();
						if (status2 > 0.0) {
							return 1;
						} else {
							return -1;
						}
					} else {
						if (status1 > 0.0) {
							return -1;
						} else {
							return 1;
						}
					}
				}
			});
		}
		Long total = (Long) pvo.getTc();
		List<ShopFoodVo> shopFoodVoList2 = new ArrayList<>();
		int pn = (pvo.getPn()-1)*pvo.getPs();
		int ps = pn+pvo.getPs();
		if(pvo.getPn()>=1&&pn<total){
			if(ps>total){
				ps=total.intValue();
			}
			for(int i=pn;i<ps;i++){
				shopFoodVoList2.add(shopFoodVoList.get(i));
			}
		}
		return ShopFoodListResponse.listAndCount(shopFoodVoList2, total);
		
	}
	
	@ApiOperation(value = "对接运营后端删除必吃商店", notes = "对接运营后端删除必吃商店")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "对接运营后端删除必吃商店") })
	@DeleteMapping(value = "/shop_food/reptile", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<?> deleteShopFood(@RequestParam(value="shopId",required=true)String shopId){
		shopfoodSer.deleteShopFoodById(shopId);
		return GenericResponse.ok();
		
	}
	
	@ApiOperation(value = "对接运营后端修改必吃商店", notes = "对接运营后端修改必吃商店")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "对接运营后端修改必吃商店") })
	@PutMapping(value = "/shop_food/reptile", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<?> updateShopFood(@RequestBody ShopFoodReptileVo shopFoodReptileVo){
		String id = shopFoodReptileVo.getId();
		ShopFoodEntity shopFood = shopfoodSer.findShopFood(id);
		if(shopFood==null){
			return GenericResponse.ng("没有该类必吃商店！");
		}
		String name = shopFoodReptileVo.getName();
		if(StringUtils.isNotBlank(name)){
			shopFood.setName(name);
		}
		String shortName = shopFoodReptileVo.getShortName();
		if(StringUtils.isNotBlank(shortName)){
			shopFood.setShortName(shortName);
		}
		String mainImgUrl = shopFoodReptileVo.getMainImgUrl();
		if(StringUtils.isNotBlank(mainImgUrl)){
			shopFood.setMainImgUrl(mainImgUrl);
		}
		Double longitude = shopFoodReptileVo.getLongitude();
		if(longitude!=null){
			shopFood.setLongitude(longitude);
		}
		Double latitude = shopFoodReptileVo.getLatitude();
		if(latitude!=null){
			shopFood.setLatitude(latitude);
		}
		
		Double avgConsum = shopFoodReptileVo.getAvgConsum();
		if(avgConsum!=null){
			shopFood.setAvgConsum(avgConsum);
		}
		Double avgScore = shopFoodReptileVo.getAvgScore();
		if(avgScore!=null){
			shopFood.setAvgScore(avgScore);
		}
		List<ShopMenusEntity> cuisinesList = shopFoodReptileVo.getCuisinesList();
		if(cuisinesList!=null&&cuisinesList.size()!=0){
			shopFood.setCuisinesList(cuisinesList);
		}
		
		List<String> tags = shopFoodReptileVo.getTags();
		if(tags!=null&&tags.size()!=0L){
			shopFood.setTags(tags);
		}
		
		String address = shopFoodReptileVo.getAddress();
		if(StringUtils.isNotBlank(address)){
			shopFood.setAddress(address);
		}
		String phone = shopFoodReptileVo.getPhone();
		if(StringUtils.isNotBlank(phone)){
			shopFood.setPhone(phone);
		}
		
		String openSchedule = shopFoodReptileVo.getOpenSchedule();
		if(StringUtils.isNotBlank(openSchedule)){
			shopFood.setOpenSchedule(openSchedule);
		}
		String zoneProvince = shopFoodReptileVo.getZoneCity();
		if(StringUtils.isNotBlank(zoneProvince)){
			shopFood.setOpenSchedule(zoneProvince);
		}
		
		shopfoodSer.save(shopFood);
		return GenericResponse.ok();
		
	}
	
	@ApiOperation(value = "(对接爬虫)爬虫接口添加商店和特色菜", notes = "(对接爬虫)爬虫接口添加商店和特色菜")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "(对接爬虫)爬虫接口添加商店和特色菜") })
	@RequestMapping(value = "/shop_food/reptile", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST)
	public ResponseEntity<?> shopFoodReptile(@RequestBody ShopFoodReptileVo shopFoodReptileVo){
		ShopFoodEntity shopFood = new ShopFoodEntity();
		BeanUtils.copyProperties(shopFoodReptileVo, shopFood);
		shopfoodSer.save(shopFood);
		return GenericResponse.ok();
		
	}
	
	@ApiOperation(value = "小程序获取特色菜列表", notes = "小程序获取特色菜列表")
	@ApiResponses({ @ApiResponse(code = 200, response = VegetRecomListResponse.class, message = "小程序获取特色菜列表") })
	@GetMapping(value="/vegets", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> getVegets( @RequestParam(value="sitesId") String sitesId){
		List<VegetRecomEntity> vegetRecoms = vegetRecomSer.findVegetRecoms(sitesId);
		List<VegetRecomVo> vegetRecomVos = new ArrayList<>();
		VegetRecomVo vegetRecomVo = null;
		if(vegetRecoms!=null){
			for(VegetRecomEntity vegetRecom:vegetRecoms){
				vegetRecomVo = new VegetRecomVo();
				BeanUtils.copyProperties(vegetRecom, vegetRecomVo);
				vegetRecomVos.add(vegetRecomVo);
			}
		}
		
		return VegetRecomListResponse.listNoCount(vegetRecomVos);
		
	}
	
	@ApiOperation(value = "小程序获取特色菜对应的店铺列表", notes = "小程序获取特色菜对应的店铺列表")
	@ApiResponses({ @ApiResponse(code = 200, response = ShopFoodListResponse.class, message = "小程序获取特色菜对应的店铺列表") })
	@GetMapping(value="/miniShopFood", produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	public ResponseEntity<?> getVeGetShops( 
			@RequestParam(value="vegetId")@ApiParam(value="推荐菜Id",required = true)String vegetId,
			@RequestParam(value="localLongitude",required=false)@ApiParam(value="当前经度",required=false)Double localLongitude,
			@RequestParam(value="localLatitude",required=false)@ApiParam(value="当前纬度",required=false)Double localLatitude){
		List<ShopFoodEntity> shopFoodList = shopfoodSer.findShopFoodByVegetId(vegetId);
		List<ShopFoodVo> shopFoodVoList = new ArrayList<>();
		ShopFoodVo shopFoodVo = null;
		for(ShopFoodEntity shopFood:shopFoodList){
			shopFoodVo = new ShopFoodVo();
			BeanUtils.copyProperties(shopFood, shopFoodVo);
			if(localLongitude!=null&&localLatitude!=null&&localLongitude!=0.00&&localLatitude!=0.00){
				Double shopLongitude = shopFoodVo.getLongitude();
				Double shopLatitude = shopFoodVo.getLatitude();
				Double distance = MathUtil.distance(localLongitude, localLatitude, shopLongitude, shopLatitude);
				shopFoodVo.setDistance(distance);
				String distanceString = MathUtil.distance(distance);
				shopFoodVo.setDistanceString(distanceString);
			}
			shopFoodVoList.add(shopFoodVo);
		}
		if (shopFoodVoList != null && shopFoodVoList.size() > 1) {

			Collections.sort(shopFoodVoList, new Comparator<ShopFoodVo>() {

				@Override
				public int compare(ShopFoodVo shopFoodVo1, ShopFoodVo shopFoodVo2) {
					Double status1 = shopFoodVo1.getAvgScore() - shopFoodVo2.getAvgScore();
					if (status1 == 0.0) {
						Double status2 = shopFoodVo1.getDistance() - shopFoodVo2.getDistance();
						if (status2 > 0.0) {
							return 1;
						} else {
							return -1;
						}
					} else {
						if (status1 > 0.0) {
							return -1;
						} else {
							return 1;
						}
					}
				}
			});
		}
		
		return ShopFoodListResponse.listNoCount(shopFoodVoList);
		
	}

}
